package com.huirui.server.interceptor;

import com.huirui.server.context.UserContext;
import com.huirui.server.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class MiniProgramLoginInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter()
                    .write("{\"error\":\"Unauthorized\"}");
            return false;
        }
        // 解析Token
        try {
            Long id = jwtUtil.parseToken(token);
            log.info("小程序用户登录：{}", id);
            UserContext.setId(id);
            return true;
        } catch (Exception exception) {
            log.error(exception.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter()
                    .write("{\"error\":\"Unauthorized\"}");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.removeId();
    }
}
